// 手写 url参数
function getQuery(str = "") {
	if (!str) {
		return;
	}

	const arr = str.split("?")[1].split("&");

	let obj = {};

	arr.forEach(param => {
		if (param.includes("=")) {
			let [key, value] = param.split("=");
			value = decodeURIComponent(value);
			if (!isNaN(+value) && value.trim() !== "") {
				obj[key] = Number(value);
			} else {
				obj[key] = value;
			}
		} else {
			obj[param] = null;
		}
	});

	return obj;
}

// console.log(getQuery('https://example.com?page=1&size=10&search=hello%20world&price=9.99&enabled=true'));

// 处理树data
const injectPaths = (nodes, parentPaths = []) => {
	return nodes.map(node => {
		const newPaths = [...parentPaths, node.value];

		const newNode = {
			...node,
			paths: newPaths,
		};

		// 递归子节点添加父节点的paths
		if (node.children) {
			newNode.children = injectPaths(node.children, newPaths);
		}

		return newNode;
	});
};

const data = [
	{
		value: "a",
		// paths: ['a'], // 增加自定义属性
	},
	{
		value: "b",
		// paths: ['b'], // 增加自定义属性
		children: [
			{
				value: "b-1",
				// paths: ['b', 'b-1'], // 增加自定义属性
				children: [
					{
						value: "b-1-1",
						// paths: ['b', 'b-1', 'b-1-1'], // 增加自定义属性
					},
				],
			},
		],
	},
];

// console.log("---injectPaths(data)->", JSON.stringify(injectPaths(data), null, 2));
function classNames() {
	let arr = Array.from(arguments);
	let strArr = [];
	arr.forEach(param => {
		if (typeof param === "string") {
			strArr.push(param);
		}
		else if (typeof param === "object" && param !== null) {
			for (let key in param) {
				if (param.hasOwnProperty(key) && param[key]) {
					// 判断对象的自身属性，并检查值是否为真
					strArr.push(key);
				}
			}
		}
		else if (typeof param === "boolean" && param) {
			strArr.push(param);
		}
		else if (param) {
			strArr.push(param);
		}
	});

	return strArr.join(" ");
}

/* classNames('foo', 'bar'); // => 'foo bar');
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' */

// 图片异步加载
const LazyLoadImage = url => {
	return new Promise((resolve, reject) => {
		let image = new Image();
		image.str = url;
		image.onload = () => {
			resolve();
		};
		image.onerror = () => {
			reject();
		};
	});
};

// LazyLoadImage('');

// 2. 实现每隔一秒打印 1,2,3,4

let count = 1;
const interval = setInterval(() => {
	console.log(count);
	count++;
	if (count > 4) {
		clearInterval(interval); // 清除定时器
	}
}, 1000); // 每隔一秒 (1000 毫秒) 执行一次

// 22. 将手机号中间四位变成*
const tel = 18877776666;
// tel = "" + tel;
// var ary = tel.split("");
// ary.splice(3, 4,"****");
// var tel1 = ary.join("");
// console.log(tel1);

"".substr(0, 3) + "****" + "".substr(7);

// 下面来看一道比较典型的问题，通过这个问题来对比几种异步编程方法：
// 红灯 3s 亮一次，绿灯 1s 亮一次，黄灯 2s 亮一次；如何让三个灯不断交替重复亮灯？

function red() {
	console.log("red");
}
function green() {
	console.log("green");
}
function yellow() {
	console.log("yellow");
}

const task = (timer, light, callback) => {
	setTimeout(() => {
		if (light === "red") {
			red();
		} else if (light === "green") {
			green();
		} else if (light === "yellow") {
			yellow();
		}
	}, timer);
};

const taskRunner = async () => {
	await task(3000, "red");
	await task(2000, "green");
	await task(2100, "yellow");
	taskRunner();
};
taskRunner();

function findMaxWord(article = "") {
	if (!article) {
		return;
	}
	article = article.toLowerCase();
	let wordList = article.match(/[a-z]/g);
	const obj = {};
	wordList.map(item => {
		if (obj[item]) {
			obj[item] = obj[item].push(item);
		} else {
			obj[item] = [].push(item);
		}
	});
	console.log("---->", obj);
}
Object.create();

function create(obj) {
	function F() {}
	F.prototype = obj;
	return new F();
}

create({ a: 1 });

function debounce(fn, wait) {
	let timer = null;
	return function () {
		let context = this,
			args = arguments;

		if (timer) {
			clearTimeout(timer);
			timer = null;
		}

		timer = setTimeout(() => {
			fn.apply(context, args);
		}, wait);
	};
}

// 函数节流的实现;
function throttle(fn, delay) {
	let curTime = Date.now();

	return function () {
		let context = this,
			args = arguments,
			nowTime = Date.now();

		// 如果两次时间间隔超过了指定时间，则执行函数。
		if (nowTime - curTime >= delay) {
			curTime = Date.now();
			return fn.apply(context, args);
		}
	};
}

//   查找文章中出现频率最高的单词
function findMostWord(article) {
	// 合法性判断
	if (!article) return;
	// 参数处理
	article = article.trim().toLowerCase();
	let wordList = article.match(/[a-z]+/g),
		visited = [],
		maxNum = 0,
		maxWord = "";
	article = " " + wordList.join("  ") + " ";
	// 遍历判断单词出现次数
	wordList.forEach(function (item) {
		if (visited.indexOf(item) < 0) {
			// 加入 visited
			visited.push(item);
			let word = new RegExp(" " + item + " ", "g"),
				num = article.match(word).length;
			if (num > maxNum) {
				maxNum = num;
				maxWord = item;
			}
		}
	});
	return maxWord + "  " + maxNum;
}
